/**
 * Framework for batch testing user profile models
 * Final project by Sergey Nepomnyachiy and Julia Polchin
 * Supervisor: Tsvi Kuflik
 *
 */
package backend;

import interfaces.LoggingInterface;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import core.environment.Defines;

/**
 * FS implementation writes to a file on a disk
 * 
 * 
 * @author Sergey and Julia
 * 
 */
public class FileSystem implements LoggingInterface {
	/**
	 * Root may represent both directory and file - depending on context
	 */
	private File root;

	/**
	 * If the path to file is not complete this method will recreate all hierarchy from root to this.root
	 */
	private void initDirs() {
		try {
			if ( ! this.root.getAbsolutePath().contains(".") )
				this.root.mkdirs(); // recreate all path
		}
		catch (Exception e) {
			//don't pay att.
		}
	}
	
	/**
	 * Construct new FS
	 * @param root The root of the logging 
	 */
	public FileSystem(File root) {
		this.root = root;
		initDirs();
	}

	/**
	 * A copy constructor
	 * @param other Some other FS
	 */
	public FileSystem(FileSystem other) {
		this.root = other.root;
		initDirs();
	}

	/**
	 * Creates "name" inside "other".
	 * Assuming (no check) "other" is in fact a directory and not a file.
	 * @param other "parent" directory for this FS element
	 * @param name the name of this FS
	 */
	public FileSystem(LoggingInterface other, String name) {
		this.root = new File(((FileSystem) other).root, name);
		initDirs();
	}


	/**
	 * Add string "who" to root
	 * @param who the string to add. A bit of hack...
	 */
	public void push(String who) {
		this.root = new File(this.root, who);
		initDirs();

	}

	@Override
	public void write(String where, String what) {
		try {
			// Create file
			final boolean append = true;
			File file = null;

			if (where != null) 
				file = new File(this.root, where);
			else
				file = this.root;
			file.createNewFile();

			FileWriter fstream = new FileWriter(file, append);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(what + "\n");

			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			Defines.printException("While writing to fs " + where + ":"
					+ e.getLocalizedMessage());
		}
	}
}
